package com.itouch.bracelet.activity;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient.ConnectCallback;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.itouch.bracelet.R;
import com.itouch.bracelet.bean.LoginResult;
import com.itouch.bracelet.bean.LoginUser;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.util.JsonAndPhpUtil;
import com.itouch.util.LocationUtil;
import com.itouch.util.StringUtils;

public class LoginActivity extends BaseActivity implements OnClickListener,
		ConnectCallback {

	private EditText username;
	private EditText password;
	private TextView login;
	private TextView register;
	private TextView lostPs;
	private double lng = 0.0;
	private double lat = 0.0;
	private LocationUtil locationUtil;

	/**
	 * 获取坐标
	 */
	private void getLocation() {
		locationUtil = new LocationUtil(this);
		if (locationUtil.isEnbled() == true) {
			locationUtil.exec();
		}
	}

	@Override
	protected int setContentViewById() {
		return R.layout.activity_login;
	}

	@Override
	protected void initViews() {
		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		login = (TextView) findViewById(R.id.login);
		register = (TextView) findViewById(R.id.register);
		lostPs = (TextView) findViewById(R.id.lost_ps);
		login.setOnClickListener(this);
		register.setOnClickListener(this);
		lostPs.setOnClickListener(this);
		getLocation();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		try {
			LoginUser user = UserCache.getOauth(this);
			// 检测是否缓存了用户
			if (user != null) {
				String name = user.getMobile();
				String pass = user.getPassword();
				username.setText(name);
				password.setText(pass);
			}
		} catch (Exception e) {

		}

	}

	@Override
	protected void initData() {

	}

	@Override
	public void onClick(View v) {
		Intent it = null;
		switch (v.getId()) {

		case R.id.register:
			it =new Intent(context, RegisterActivity.class);
			startActivity(it);
			break;
		
		case R.id.lost_ps:
			it =new Intent(context, LostPSActivity.class);
			startActivity(it);
			
			break;
		case R.id.login:
//			Intent itt = new Intent(this, MainActivity.class);
//			startActivity(itt);
//			LoginActivity.this.finish();
			
			
			if (username.getText().toString().length() < 2) {
				Toast.makeText(this, "请输入正确的用户名", Toast.LENGTH_LONG).show();
				return;
			}
			if (password.getText().toString().length() < 5) {
				Toast.makeText(this, "请输入正确的密码", Toast.LENGTH_LONG).show();
				return;
			}
			new LoginAsync(this).execute();
			break;

		default:
			break;
		}
	}

	class LoginAsync extends AsyncTask<String, String, String> {

		private Context context;

		public LoginAsync(Context context) {
			super();
			this.context = context;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			show();
		}

		// password=211289&phone=15211111111&lat=22.1234&lng=33.4321&type=1&appcode=12&mobicode=11
		@Override
		protected String doInBackground(String... params) {
			List<NameValuePair> lists = new ArrayList<NameValuePair>();
			lists.add(new BasicNameValuePair("phone", username.getText()
					.toString()));
			lists.add(new BasicNameValuePair("password", password.getText()
					.toString()));
			lists.add(new BasicNameValuePair("appcode", Constants.APP_CODE));

			if (locationUtil.getMyLocation() != null) {
				lat = locationUtil.getMyLocation().getLatitude();
				lng = locationUtil.getMyLocation().getLongitude();
			}
			lists.add(new BasicNameValuePair("lng", lng + ""));
			lists.add(new BasicNameValuePair("lat", lat + ""));
			lists.add(new BasicNameValuePair("type", "1"));
			lists.add(new BasicNameValuePair("mobicode",
					"PushManager.getInstance().getClientid(LoginActivity.this)"));
			String ss = JsonAndPhpUtil.postHttpData(Constants.LOGIN_BY_PHONE,
					lists, context);
			 Log.i("LOGIN_BY_PHONE", "LOGIN_BY_PHONE" + ss);
			return ss;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			Log.e("LoginActivity", "---------result---:" + result);
			if (!StringUtils.isNull(result)) {
				LoginResult a = new Gson().fromJson(result, LoginResult.class);
				if (a != null && a.isFlag()) {
					
					LoginUser user = a.getRows();
					RongIM.getInstance().connect(user.getToken(),
							LoginActivity.this);
					user.setPassword(password.getText().toString());
					UserCache.saveOAuth(user, context);
				} else {
					disMiss();
					// 用户名密码错误
					String message = "用户名或密码错误!";
					if (a != null) {
						message = a.getMsg();
					}
					Toast.makeText(context, message + " ", Toast.LENGTH_LONG)
							.show();
				}
			} else {
				disMiss();
				// 网络失败
				Toast.makeText(context, "请求失败，请稍后再试..", Toast.LENGTH_LONG)
						.show();
			}
		}
	}

	@Override
	public void onSuccess(String userId) {
		disMiss();
		Log.e("LoginActivity", "---------userId-------&&---:" + userId);
		Intent it = new Intent(this, MainActivity.class);
		startActivity(it);
		LoginActivity.this.finish();

	}

	@Override
	public void onError(ErrorCode errorCode) {
		disMiss();
		Log.e("LoginActivity", "---------userId----------:" + errorCode);
	}
}
